<script setup lang="ts">
import {
  ref,
  defineProps,
  defineEmits,
  computed,
  reactive,
  onMounted
} from 'vue';
import {
  ElMessage,
  ElLoading,
  ElNotification,
  UploadProps,
  UploadUserFile
} from 'element-plus';
import {
  getDictDataType,
  addUserFileApi,
  getUserFileListApi,
  deleteUserFileApi
} from '@/api/user';
const props = defineProps({
  DictType: {
    type: String,
    default: function () {
      return '';
    }
  },
  fileList: {
    type: Array,
    default: function () {
      return [];
    }
  },
  userInfo: {
    type: Object,
    default: function () {
      return {};
    }
  }
});
let tabList = ref([]);
let uploadList = ref<any>([]);
let loading = reactive<any>(null);
let activeName = ref('');
const emit = defineEmits(['update:fileList']);

getTabList();
function getTabList() {
  getDictDataType(props.DictType).then(re => {
    tabList.value = re.response;
    tabList.value.forEach(function (item: any) {
      item.fileList = [];
    });
    activeName.value = re.response[0].dictCode;
  });
}

function getUserFileList() {
  console.log(props.userInfo);
  getUserFileListApi({ userId: props.userInfo.id }).then(re => {
    if (re.code === 1) {
      re.response.forEach(function (item) {
        tabList.value.forEach(function (items: any, index) {
          if (item.dictCode == items.dictCode) {
            items.fileList.push({
              name: item.fileUrl.split('/')[item.fileUrl.split('/').length - 1],
              url: item.fileUrl,
              id: item.id
            });
          }
        });
      });
    }
  });
}
onMounted(() => {
  setTimeout(() => {
    getUserFileList();
  }, 1000);
});

function uploadProgress() {
  loading = ElLoading.service({
    lock: true,
    text: '文件上传中…',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.5)'
  });
}
function arrayBufferToBase64(buffer) {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}
function handleBeforeUpload(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (event) => {
      if (event.target != null && event.target.result != null) {
        const img = new Image();
        if (typeof event.target.result === 'string') {
          img.src = event.target.result;
        } else if (event.target.result instanceof ArrayBuffer) {
          img.src = 'data:image/png;base64,' + arrayBufferToBase64(event.target.result);
        }
        // img.src = event.target.result;
        img.onload = () => {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          canvas.width = 200; // 设置压缩后图片宽度
          // canvas.height = (img.height / img.width) * 300; // 根据宽度等比缩放高度
          canvas.height = 300; // 根据宽度等比缩放高度
          if (ctx) {
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

          } else {
            // 处理ctx为null的情况
            console.error('无法获取绘图上下文');
            // 可以选择设置一个备用图像或者进行其他错误处理
          }
          canvas.toBlob(
            (blob) => {
              if (blob) {
                resolve(new File([blob], file.name, { type: 'image/jpeg', lastModified: Date.now() }));

              } else {
                // 处理blob为null的情况
                console.error('Blob is null');
                // 可以选择resolve一个错误对象或者进行其他错误处理
                resolve(null); // 或者resolve一个表示错误的对象
              }
            },
            'image/jpeg',
            0.9 // 压缩质量，0.9表示压缩率为90%
          );
        };

      }
    };
  })
}

// 上传接口调取成功status为200
function uploadSuccess(res, file, fileList, item, index) {
  fileList.forEach(items => {
    items.dictCode = item.dictCode;
    items.dictIndex = index;
    items.type = items.raw?.type;
  });
  props.fileList[index] = fileList;
  // currentArr.push(file);
  // console.log(res);
  console.log(file);
  console.log(fileList);
  console.log(item);
  if (res.code === 1) {
    // 文件上传成功
    // ElNotification.success({
    //   title: '成功',
    //   message: `${file.name}文件上传成功！`
    // });
    console.log(props.userInfo);
    addUserFile(
      {
        fileUrl: res.response.path,
        fileType: file.type,
        fileName: file.name,
        dictCode: file.dictCode,
        userId: props.userInfo.id
      },
      fileList,
      file.uid
    );
    loading.close();
  } else {
    uploadError();
  }
}
function addUserFile(file, fileList, uid) {
  addUserFileApi(file).then(re => {
    if (re.code === 1) {
      fileList.forEach(function (item) {
        if (item.uid == uid) {
          item.id = re.response;
        }
      });
      ElNotification.success({
        title: '成功',
        message: `文件上传成功！`
      });
    } else {
      uploadError();
    }
  });
}
function uploadError() {
  loading.close();
  ElMessage.error('文件上传失败，请检查文件大小或文件格式');
}
function toShow(file, uploadFiles) {
  var link = document.createElement("a"); //定义一个a标签
		      link.download = file.name; //下载后的文件名称
		      link.href = file.url; //需要生成一个 URL 来实现下载
		      link.click(); //模拟在按钮上实现一次鼠标点击
		      window.URL.revokeObjectURL(link.href);
}
function handleRemove(file, uploadFiles, item, index) {
  deleteUserFileApi({ ids: [file.id] }).then(re => {
    if (re.code === 1) {
      ElNotification.success({
        title: '成功',
        message: `文件删除成功！`
      });
    }
  });
}
</script>

<template>
  <el-tabs type="border-card" class="train-tab" v-model="activeName">
    <el-tab-pane v-for="(item, index) in tabList" :label="item.dictLabel" :name="item.dictCode" :key="index">
      <el-upload name="file" :data="{ folder: 'train/user' }" accept="image/*" action="/api/upload/folder/file"
        v-model:file-list="item.fileList" :show-file-list="true" list-type="picture" :on-progress="uploadProgress"
        :before-upload="handleBeforeUpload" :on-remove="(file, uploadFiles) => {
          return handleRemove(file, uploadFiles, item, index);
        }
          " :on-success="(response, file, fileList) => {
            return uploadSuccess(response, file, fileList, item, index);
          }
            " :on-error="uploadError"  >
            :on-preview="toShow"
        <el-button type="primary" size="small" class="link-left wdd-button-mini">上传{{ item.dictLabel }}</el-button>
      </el-upload>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
    </el-tab-pane>
  </el-tabs>
</template>

<style scoped lang="scss"></style>
